<template>
  <div class="drawer-container">
    <el-drawer
      :visible.sync="drawerVisible"
      :direction="mergedConfig.direction"
      :size="mergedConfig.size"
      :with-header="false"
      :before-close="handleClose"
      :wrapperClosable="mergedConfig.wrapperClosable"
      :show-close="false"
      custom-class="custom-drawer"
    >
      <!-- 整个抽屉内容包装器 -->
      <div class="drawer-wrapper">
        <!-- 自定义标题区域 -->
        <div class="custom-header" :style="headerStyle">
          <div class="header-content">
            <span class="header-title">{{ mergedConfig.title }}</span>
            <el-button
              v-if="mergedConfig.showClose"
              class="close-button"
              type="text"
              @click="handleClose"
            >
              <i class="el-icon-close"></i>
            </el-button>
          </div>
        </div>

        <!-- 动态内容区域 -->
        <div class="drawer-content" :style="drawerContentStyle">
          <slot v-if="$slots.content" name="content"></slot>
          <slot v-else-if="$slots.default"></slot>
          <div v-else class="default-content">
            <p>{{ mergedConfig.contentText }}</p>
            <div
              v-for="i in mergedConfig.contentItems"
              :key="i"
              class="content-item"
            >
              {{ mergedConfig.itemText }} {{ i }} - {{ mergedConfig.contentText }}
            </div>
          </div>
        </div>

        <!-- 动态底部按钮 -->
        <div class="drawer-footer" v-if="mergedConfig.showFooter && hasButtons" :style="footerAlignStyle">
          <el-button
            v-for="(button, index) in visibleButtons"
            :key="button.key || index"
            :type="button.type || 'default'"
            :size="button.size || 'medium'"
            :plain="button.plain"
            :round="button.round"
            :circle="button.circle"
            :loading="getButtonLoading(button)"
            :disabled="getButtonDisabled(button)"
            :icon="button.icon"
            :class="button.customClass"
            @click="handleButtonClick(button)"
          >
            {{ button.text }}
          </el-button>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script>
// 默认配置
const DEFAULT_CONFIG = {
  title: '表单编辑',
  direction: 'rtl',
  size: '50%',
  contentHeight: 'auto',
  contentText: '这是一段信息，下面将生成足够多的内容来测试滚动效果。',
  itemText: '内容项',
  contentItems: 20,
  showFooter: true,
  wrapperClosable: true,
  showClose: true,
  headerBgColor: '#FFFFFF',
  contentBgColor: '#f5f7fa',
  footerBgColor: '#FFFFFF',
  footerAlign: 'right',
  buttons: [
    {
      key: 'cancel',
      text: '取消',
      type: 'default',
      position: 'left',
      isShow: true,
      autoClose: true
    },
    {
      key: 'submit',
      text: '提交',
      type: 'primary',
      position: 'right',
      isShow: true,
      autoClose: false
    }
  ]
}

export default {
  name: 'DynamicDrawer',
  props: {
    config: {
      type: Object,
      default: () => ({})
    },
    visible: {
      type: Boolean,
      default: false
    },
    buttonLoading: {
      type: Object,
      default: () => ({})
    },
    buttonDisabled: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      drawerVisible: this.visible
    }
  },
  computed: {
    // 合并配置
    mergedConfig() {
      return { ...DEFAULT_CONFIG, ...this.config }
    },

    // 可见按钮列表
    visibleButtons() {
      if (!this.mergedConfig.buttons || !Array.isArray(this.mergedConfig.buttons)) {
        return []
      }
      return this.mergedConfig.buttons.filter(button => button.isShow !== false)
    },

    // 是否有显示的按钮
    hasButtons() {
      return this.visibleButtons.length > 0
    },

    // 抽屉内容样式
    drawerContentStyle() {
      const style = {
        height: '100%',
        display: 'flex',
        flexDirection: 'column',
        backgroundColor: this.mergedConfig.contentBgColor,
        padding: '15px'
      }

      if (this.mergedConfig.direction === 'rtl' || this.mergedConfig.direction === 'ltr') {
        style.maxHeight = this.mergedConfig.contentHeight === 'auto'
          ? 'calc(100vh - 120px)'
          : this.mergedConfig.contentHeight
        style.overflow = 'auto'
      }

      return style
    },

    // 头部样式
    headerStyle() {
      return {
        backgroundColor: this.mergedConfig.headerBgColor
      }
    },

    // 底部对齐样式
    footerAlignStyle() {
      const alignMap = {
        'left': 'flex-start',
        'center': 'center',
        'right': 'flex-end'
      }
      return {
        backgroundColor: this.mergedConfig.footerBgColor,
        justifyContent: alignMap[this.mergedConfig.footerAlign] || 'flex-end'
      }
    }
  },
  watch: {
    visible(newVal) {
      this.drawerVisible = newVal
    },

    drawerVisible(newVal) {
      this.$emit('update:visible', newVal)
      this.$emit('visible-change', newVal)
    }
  },
  methods: {
    // 获取按钮加载状态
    getButtonLoading(button) {
      return this.buttonLoading[button.key] || false
    },

    // 获取按钮禁用状态
    getButtonDisabled(button) {
      return this.buttonDisabled[button.key] || false
    },

    // 统一的按钮点击事件处理
    handleButtonClick(button) {
      const eventData = {
        buttonKey: button.key,
        buttonText: button.text,
        buttonConfig: button,
        drawerConfig: this.mergedConfig
      }

      // 发射按钮点击事件
      this.$emit('button-click', eventData)

      // 如果配置了点击后关闭抽屉，则关闭
      if (button.autoClose) {
        this.drawerVisible = false
      }
    },

    // 关闭抽屉
    handleClose(done) {
      if (this.mergedConfig.beforeClose) {
        this.mergedConfig.beforeClose(done)
      } else {
        this.$confirm('确认关闭？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$emit('before-close')
          if (typeof done === 'function') {
            done()
          } else {
            this.drawerVisible = false
          }
        }).catch(() => {
          // 取消关闭
        })
      }
    }
  },
  mounted() {
    // 监听 ESC 键
    const handleEsc = (e) => {
      if (e.keyCode === 27 && this.drawerVisible && this.mergedConfig.wrapperClosable) {
        this.handleClose()
      }
    }
    document.addEventListener('keydown', handleEsc)
    this.$once('hook:beforeDestroy', () => {
      document.removeEventListener('keydown', handleEsc)
    })
  }
}
</script>

<style scoped>
.drawer-container {
  display: flex;
  justify-content: center;
  align-items: center;
}

.drawer-wrapper {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.custom-header {
  padding: 14px 20px;
  border-bottom: 1px solid #e8e8e8;
  background-color: #fff;
  flex-shrink: 0;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-title {
  font-weight: 600;
  font-size: 16px;
  color: #303133;
}

.close-button {
  padding: 0;
  width: 24px;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.close-button i {
  font-size: 16px;
  color: #909399;
}

.close-button:hover i {
  color: #409EFF;
}

.drawer-content {
  flex: 1;
  overflow: auto;
}

.default-content {
  height: 100%;
}

.content-item {
  padding: 12px 0;
  border-bottom: 1px solid #f0f0f0;
  margin-bottom: 8px;
  font-size: 14px;
  color: #606266;
}

.drawer-footer {
  position: sticky;
  bottom: 0;
  background: white;
  z-index: 10;
  padding: 16px 20px;
  border-top: 1px solid #ebeef5;
  display: flex;
  gap: 12px;
  flex-shrink: 0;
}
</style>

<style>
:deep(.custom-drawer .el-drawer__header) {
  display: none !important;
}

:deep(.custom-drawer .el-drawer__title) {
  display: none !important;
}

:deep(.custom-drawer .el-drawer__close-btn) {
  display: none !important;
}

:deep(.custom-drawer .el-drawer__body) {
  padding: 0 !important;
  margin: 0 !important;
  display: flex !important;
  flex-direction: column !important;
  height: 100% !important;
  overflow: hidden !important;
}

/* 响应式调整 */
@media (max-width: 768px) {
  :deep(.custom-drawer .el-drawer) {
    width: 100% !important;
  }

  .drawer-content {
    padding: 15px !important;
  }

  .drawer-footer {
    padding: 15px;
  }
}

/* 滚动条样式 */
.custom-drawer .el-drawer__body::-webkit-scrollbar {
  width: 6px;
}

.custom-drawer .el-drawer__body::-webkit-scrollbar-track {
  background: #f1f1f1;
}

.custom-drawer .el-drawer__body::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.custom-drawer .el-drawer__body::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}
</style>
